package cn.enine.tbcharge.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.LitePal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.adapter.CommonAdapter;
import cn.enine.tbcharge.adapter.ViewHolder;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.LvHeightUtil;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.RegexUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.enine.tbcharge.utils.AidlUtil;

public class ZfChooseActivity extends MyBaseActivity {

    Context con = ZfChooseActivity.this;
    AppSfMain obj;
    private TextView title, saveBtn, totalfy, pjdy, sftotalfy;
    private EditText name, idno, phone;
    LinearLayout back, llzfzt;
    String url = "";

    List<AppSfSub> list;
    private int pageNum1 = 1;// 无关键字页数
    private EditText key;
    private String mainid = "";
    RadioGroup zftype;
    RadioButton zftype1,zftype2,zftype3;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_zf_choose);
        //姓名
        name = (EditText) findViewById(R.id.name);
        idno = (EditText) findViewById(R.id.idno);
        phone = (EditText) findViewById(R.id.phone);
        totalfy = (TextView) findViewById(R.id.totalfy);
        sftotalfy = (TextView) findViewById(R.id.sftotalfy);
        back = (LinearLayout) findViewById(R.id.back);
        llzfzt = (LinearLayout) findViewById(R.id.llzfzt);

        title = (TextView) findViewById(R.id.title);
        saveBtn = (TextView) findViewById(R.id.uname);
        title.setText("收费支付");
        saveBtn.setText("支付");
        pjdy = (TextView)findViewById(R.id.pjdy);
        pjdy.setVisibility(View.VISIBLE);

        zftype1 = (RadioButton)findViewById(R.id.zftype1);
        zftype2 = (RadioButton)findViewById(R.id.zftype2);
        zftype3 = (RadioButton)findViewById(R.id.zftype3);
    }
    @Override
    protected void initData() {
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (AppSfMain) getIntent().getExtras().getSerializable("b");
            mainid = obj.getNid();
            init(obj);
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getInfo();
        } else {
            list = LitePal.where("mainid = ?", mainid).order(" addtime asc").find(AppSfSub.class);
            if(null  != list) {
                BigDecimal total = new BigDecimal("0");
                for (AppSfSub appSfSub : list) {//"护理费                    25"
                    total = total.add(new BigDecimal(appSfSub.getFy()));
                }
                totalfy.setText(total + "");
                if (obj != null && null != obj.getZfstate() && obj.getZfstate() == 1) {
                    sftotalfy.setText(obj.getSftotalfy() + "");
                } else {
                    sftotalfy.setText(total + "");
                }
            }
        }
    }

    private void init(final AppSfMain obj) {
        if (obj != null && !StringUtils.isEmpty(obj.getName())) {
            name.setText(obj.getName());
        }

        if (obj != null && !StringUtils.isEmpty(obj.getIdno())) {
            idno.setText(obj.getIdno());
        }

        if (obj != null && !StringUtils.isEmpty(obj.getPhone())) {
            phone.setText(obj.getPhone());
        }

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(new Intent(con, SflistActivity.class));
            }
        });
        initRadioButton();
        if(null != obj.getZfstate() && obj.getZfstate()==1) {
            saveBtn.setVisibility(View.GONE);
            llzfzt.setVisibility(View.VISIBLE);
            totalfy.setFocusable(false);
            totalfy.setFocusableInTouchMode(false);
            sftotalfy.setFocusable(false);
            sftotalfy.setFocusableInTouchMode(false);
            phone.setFocusable(false);
            phone.setFocusableInTouchMode(false);
            idno.setFocusable(false);
            idno.setFocusableInTouchMode(false);
            name.setFocusable(false);
            name.setFocusableInTouchMode(false);
            zftype1.setFocusable(false);
            zftype1.setFocusableInTouchMode(false);
            zftype2.setFocusable(false);
            zftype2.setFocusableInTouchMode(false);
            zftype3.setFocusable(false);
            zftype3.setFocusableInTouchMode(false);
//            设置不可编辑状态：
//            editText.setFocusable(false);
//            editText.setFocusableInTouchMode(false);
//            设置可编辑状态：
//            editText.setFocusableInTouchMode(true);
//            editText.setFocusable(true);
//            editText.requestFocus();
        }
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //boolean validate = BinderUtil.copyDataToView(grjbxx_fh.this, obj);
                String nameText = name.getText().toString();
                String idnoText = idno.getText().toString();
                String phoneText = phone.getText().toString();
                String totalfyText = totalfy.getText().toString();
                String sftotalfyText = sftotalfy.getText().toString();
                if (null == nameText || "".equals(nameText)) {
                    MyToastUtil.ShowToast(con, "请输入姓名");
                } else if (null != nameText && !"".equals(nameText) && nameText.length() > 10) {
                    MyToastUtil.ShowToast(con, "请输入正确汉字姓名切不能超过10个字符");
                } else if (null == sftotalfyText || "".equals(sftotalfyText)) {
                    MyToastUtil.ShowToast(con, "请填写正确实付金额");
                }  else if (null != phoneText && !"".equals(phoneText) && !RegexUtils.isMobileExact(phoneText)) {
                    MyToastUtil.ShowToast(con, "请输入正确手机号码");
                } else if (null != idnoText && !"".equals(idnoText) && !RegexUtils.isIDCard18(idnoText)) {
                    MyToastUtil.ShowToast(con, "请输入正确身份证号码");
                } else {//验证通过
                    obj.setName(nameText);
                    obj.setIdno(idnoText);
                    obj.setPhone(phoneText);
                    obj.setSftotalfy(sftotalfyText);
                    obj.setZfstate(1);

                    if (NetWorkUtils.isNetworkConnected(con)) {
                        //网络连接时
                        url = HttpUrl.zfEditSfmain;
                        RequestParams ps = new RequestParams();
                        ps.add("entity.NID", obj.getNid());
                        ps.add("entity.NAME", nameText);
                        ps.add("entity.IDNO", idnoText);
                        ps.add("entity.PHONE", phoneText);
                        ps.add("entity.ZFTYPE", obj.getZftype()+"");
                        ps.add("entity.SFTOTALFY", sftotalfyText);
                        ps.add("entity.PHONE", phoneText);
                        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                        ps.add("type", "2");
                        UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(String content) {
                                super.onSuccess(content);
                                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                                if (ret.getCode().equals("200")) {
                                    MyToastUtil.ShowToast(con, "成功");
                                    Bundle b = new Bundle();
                                    b.putSerializable("b", obj);
                                    finish();
                                    startActivity(new Intent(con, SfaddActivity.class).putExtras(b).putExtra("type", "edit"));
                                }
                            }

                            @Override
                            public void onFailure(Throwable error) {
                                super.onFailure(error);
                                MyToastUtil.ShowToast(con, "失败");
                            }
                        });
                    }else{
                        //网络不通,保存本地
                        List<AppSfMain> mainlist = LitePal.where("nid = ?", mainid).find(AppSfMain.class);
                        if(null != mainlist && mainlist.size()==1){
                            AppSfMain appSfMain= (AppSfMain)mainlist.get(0);
                            obj.setTotalfy(totalfyText);
                            obj.setSftotalfy(sftotalfyText);
                            obj.setZfstate(1);
                            obj.update(appSfMain.getId());
                        }
                        Bundle b = new Bundle();
                        b.putSerializable("b", obj);
                        finish();
                        startActivity(new Intent(con, SfaddActivity.class).putExtras(b).putExtra("type", "edit"));
                    }
                }
            }
        });
        pjdy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(baseApp.isAidl()){
                    AidlUtil aidlUtil= AidlUtil.getInstance();
                    aidlUtil.printText(SharedPreferencesUtils.getParam(con,"yljgname","").toString(),36,true, false, 2,1);
                    aidlUtil.printText("收费票据",36,true, false, 2,1);
                    String phoneStr = obj.getPhone()==null? "" :obj.getPhone();
                    aidlUtil.printText("姓名："+obj.getName()+"  联系方式："+phoneStr,22,true, false, 1, 1);
                    aidlUtil.printXian(1,0);
                    aidlUtil.printText("项目名称                 金额",22,true, false, 1, 1);
                    aidlUtil.printXian(2,0);
                    BigDecimal total = new BigDecimal("0");
                    if(null ==list || list.size()<=0){
                        aidlUtil.printText("暂无明细", 22, true, false, 1, 1);
                    }else {
                        for (AppSfSub appSfSub : list) {//"护理费                    25"
                            total = total.add(new BigDecimal(appSfSub.getFy()));
                            aidlUtil.printText(StringUtils.getSpaceStr(appSfSub.getXmname())+appSfSub.getFy(), 22, true, false, 1, 1);
                        }
                    }
                    String zfStr  ="现金支付";
                    if(obj.getZfstate()==1){
                        zfStr  ="现金支付";
                    }else  if(obj.getZfstate()==2){
                        zfStr  ="支付宝支付";
                    }else  if(obj.getZfstate()==3){
                        zfStr  ="微信支付";
                    }
                    aidlUtil.printXian(1,1);
                    aidlUtil.printText("应付金额："+total+"  实付金额："+obj.getSftotalfy(),22,true, false, 1, 1);
                    aidlUtil.printText("支付类型："+zfStr,22,true, false, 1, 1);
                    aidlUtil.printText("收费日期："+obj.getTbtime(),22,true, false, 1, 1);
                    aidlUtil.printText("收费员："+obj.getYsname(),22,true, false, 1, 4);
                }else{
                    //BluetoothUtil.sendData(send);
                }
            }
        });
    }

    private void initRadioButton(){
        //问题1
        zftype = findViewById(R.id.zftype);
        if (obj != null ) {
           if(null == obj.getZftype()){
               obj.setZftype(1);
           }
            switch (obj.getZftype()) {
                case 1:
                    zftype.check(R.id.zftype1);
                    break;
                case 2:
                    zftype.check(R.id.zftype2);
                    break;
                case 3:
                    zftype.check(R.id.zftype3);
                    break;
            }
        }else{
            obj.setZftype(1);
        }
        zftype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.zftype1) {
                    obj.setZftype(1);
                } else if (checkedId == R.id.zftype2){
                    obj.setZftype(2);
                }else if (checkedId == R.id.zftype3) {
                    obj.setZftype(3);
                }
            }
        });
    }

    public void getInfo() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("mainid", obj.getNid());
        UserClient.get(HttpUrl.GetSfsubList, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                super.onFailure(statusCode, error, content);
                MyToastUtil.ShowToast(con, "请求失败");
            }
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<AppSfSub> ll = JSON.parseArray(ret.getList(), AppSfSub.class);
                    if (pageNum1 == 1)
                        list = new ArrayList<AppSfSub>();
                    BigDecimal total = new BigDecimal("0");
                    for (int i = 0; i < ll.size(); i++) {
                        AppSfSub appSfSub = ll.get(i);
                        total = total.add(new BigDecimal(appSfSub.getFy()));
                        list.add(appSfSub);
                    }
                    if(null  != list) {
                        totalfy.setText(total + "");
                        if (obj != null && null != obj.getZfstate() && obj.getZfstate() == 1) {
                            sftotalfy.setText(obj.getSftotalfy() + "");
                        } else {
                            sftotalfy.setText(total + "");
                        }
                    }
                } else {
                    MyToastUtil.ShowToast(con, "获取错误");
                }
            }
        });
    }
}
